"""主入口文件"""
import traceback
from agents import create_agent
from tools import DataQueryTool, PlanManagerTool, WebBrowserTool
from config.config import DEFAULT_MODEL
from langchain_core.messages import HumanMessage


def main():
    """主函数"""
    all_tools = DataQueryTool + PlanManagerTool + WebBrowserTool
    agent = create_agent(all_tools, DEFAULT_MODEL)
    
    print("Agent已启动，输入 'quit' 退出\n")
    
    while True:
        user_input = input("你: ")
        
        if user_input.lower() in ['quit', 'exit', '退出']:
            print("再见！")
            break
        
        if not user_input.strip():
            continue
        
        try:
            print("\nAgent: ", end="", flush=True)
            
            for stream_mode, chunk in agent.stream(
                {"messages": [HumanMessage(content=user_input)]},
                stream_mode=["updates", "messages"]
            ):
                if stream_mode == "messages":
                    message_chunk, metadata = chunk
                    if hasattr(message_chunk, 'content') and message_chunk.content:
                        print(message_chunk.content, end="", flush=True)
            
            print("\n")  # 换行
            
        except Exception as e:
            # 获取详细的错误信息
            error_type = type(e).__name__  # 错误类型名称
            error_message = str(e)  # 错误消息
            error_traceback = traceback.format_exc()  # 完整的堆栈跟踪
            
            # 打印详细的错误信息
            print("\n" + "="*60)
            print("❌ 发生错误")
            print("="*60)
            print(f"错误类型: {error_type}")
            print(f"错误消息: {error_message}")
            print(f"用户输入: {user_input}")
            
            # 针对常见错误提供友好的提示
            if "APIConnectionError" in error_type or "Connection error" in error_message:
                print("\n💡 提示: 这通常是 API 连接配置问题，请检查：")
                print("   1. 是否在 .env 文件中配置了 OPENAI_API_KEY？")
                print("   2. 是否在 .env 文件中配置了 OPENAI_BASE_URL？")
                print("   3. OPENAI_BASE_URL 是否正确（应包含 http:// 或 https:// 前缀）？")
                print("   4. 网络连接是否正常？")
                print("   示例配置：")
                print("   OPENAI_API_KEY=your_api_key_here")
                print("   OPENAI_BASE_URL=https://dashscope.aliyuncs.com/compatible-mode/v1")
            elif "UnsupportedProtocol" in error_traceback:
                print("\n💡 提示: URL 格式错误，请确保 OPENAI_BASE_URL 包含协议前缀（http:// 或 https://）")
            
            print("\n详细堆栈跟踪:")
            print("-"*60)
            print(error_traceback)
            print("="*60 + "\n")


if __name__ == "__main__":
    main()

